<template>
	<div class="app-container">
		<statistic-bar
			ref="box1"
			:payload-data="statisticPayload"
		></statistic-bar>
		<jk-operation-card>
			<div ref="box2" class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-button icon="el-icon-plus" type="primary" :has-permission="true" class="margin-5-0 item-gap" @click="onAddBtn">新增</jk-button>
					<el-button size="small" @click="versionRecordDialogState = true">版本追溯</el-button>
					<!--<jk-report-button :permission-prefix="prefix" class="margin-5-0" :loading="exportLoading" @click="onReportBtn"></jk-report-button>-->
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.workshopId" :option-list="workshopList" :clearable="false" placeholder="区域" class="search-bar-item-size2 margin-5-0 item-gap" @change="onWorkshopChange"></jk-select>
					<jk-select v-model="searchParams.processCode" value-key-name="code" :option-list="garbledProcess" size="small" placeholder="工序" class="search-bar-item-size1 margin-5-0 item-gap">
						<!--						<el-option v-for="(item, index) in processList" :key="index" :value="item.processCode" :label="item.processName"></el-option>-->
					</jk-select>
					<jk-select v-model="searchParams.auditState" :option-list="reportStateList" placeholder="状态" clearable class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<jk-date-picker v-model="searchParams.belongDate" class="search-bar-item-size2 item-gap" type="date" placeholder="报工日期" />
					<jk-select v-model="searchParams.shiftId" :option-list="shiftList" placeholder="班次" size="small" class="search-bar-item-size1 margin-5-0 item-gap" clearable />
					<jk-search-input v-model="searchParams.code" placeholder="单据编号" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
			<jk-table ref="jkTable" :loading="tableLoading" :data="tableData" :height="tableHeight + 40">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<span v-if="item.keyName === 'code'" class="link-style" @click="onDetailBtn(scope.row)">{{ scope.row.code }}</span>
						<jk-state-bar v-else-if="item.keyName === 'auditState'" :state="scope.row.auditState" :state-list="reportStateList"></jk-state-bar>
						<span v-else-if="item.keyName === 'generateType'">{{ !scope.row.generateType ? '自动' : '手动' }}</span>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="180">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button :disabled="scope.row.auditState !== 0" icon="el-icon-edit" class="item-gap" size="mini" type="success" @click="onEditBtn(scope.row)">编辑</jk-button>
							<el-dropdown trigger="click" @command="onDropdownChange($event, scope.row)">
								<el-button type="primary" size="mini" class="el-dropdown-link">
									更多<i class="el-icon-arrow-down el-icon--right"></i>
								</el-button>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item
										v-for="(item) in dropdownOption"
										:key="item.code"
										:command="item.code"
										:disabled="item.allowState || item.allowState === 0 ? scope.row.auditState !== item.allowState : false"
										:style="{display: !item.isShow ? 'none' : 'block'}"
									>
										<span :class="`${item.icon} item-gap`"></span>
										<span>{{ item.name }}</span>
									</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box3" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-operation-card>
		<version-record-dialog
			:process-code="searchParams.processCode"
			:dialog-state="versionRecordDialogState"
			@on-visible-change="onVisibleChange"
		></version-record-dialog>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig } from '/src/utils/jk/jk-tool';
    import {
        productionPrdReportDelete,
        productionPrdReportPage,
        productionPrdReportExportExcel,
        productionPrdReportUpdateStatus
    } from '/src/api/production/xsReport';
    import { machineManagerMachineGetAllRunState } from '../../../api/intelligence/index';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import versionRecordDialog from './version-record-dialog';
    import { reportStateList } from '../../../utils/jk/status-option-list';
    import statisticBar from './components/statistic-bar';
    import { workforcemanagementShiftPage } from '../../../api/schedule/shift';
    import supplementaryPlanMx from '../order/components/form-box/supplementaryPlanMx';

    export default {
        components: {
            statisticBar,
            versionRecordDialog
        },
        mixins: [calHeight, getMenuColumn, handlerCache, supplementaryPlanMx],
        data() {
            return {
                prefix: 'production:prdReport',
                apiItem: {
                    'page': productionPrdReportPage,
                    'exportExcel': productionPrdReportExportExcel,
                    'delete': productionPrdReportDelete
                },
                versionRecordDialogState: false,
                reportTypeList: [
                    { id: 0, name: '自动' },
                    { id: 1, name: '手动' }
                ],
                statisticPayload: {},
                reportStateList: reportStateList,
                dataId: null,
                workshopList: [],
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                processList: [],
                garbledProcess: [],
                shiftList: [],
                totalCount: 0,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    code: '',
                    processCode: '',
                    belongDate: '',
                    shiftId: '',
                    processName: '',
                    auditState: null,
                    workshopId: null
                },
                dropdownOption: [
                    { code: 'DETAIL', name: '详情', isShow: true, icon: 'el-icon-view', allowState: null, api: null },
                    { code: 'RELEASE', name: '审核', isShow: true, icon: 'el-icon-s-check', allowState: 0, api: productionPrdReportUpdateStatus },
                    { code: 'CANCEL_RELEASE', name: '撤销审核', isShow: true, icon: 'el-icon-circle-close', allowState: 1, api: productionPrdReportUpdateStatus },
                    { code: 'DELETE', name: '删除', isShow: true, icon: 'el-icon-delete', allowState: 0, api: productionPrdReportDelete }
                ]
            };
        },
        methods: {
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            getStatisticPayload() {
                this.statisticPayload = {
                    workshopId: this.searchParams.workshopId,
                    processCode: this.searchParams.processCode
                };
            },
            onVisibleChange(e) {
                this.versionRecordDialogState = e;
            },
            onDropdownChange(type, { id }) {
                const optionItem = this.dropdownOption.find(x => x.code === type);
                if (optionItem) {
                    if (optionItem.code === 'DETAIL') {
                        this.onDetailBtn({ id });
                    } else {
                        this.$confirm(`确定"${optionItem.name}"吗？`, '提示', { type: 'warning' }).then(() => {
                            optionItem.api({ id: id }).then(res => {
                                if (res.data.status === 200) {
                                    this.getListRequest();
                                }
                            });
                        }).catch(() => {});
                    }
                }
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            transformRouterName() {
                let name = this.searchParams.processCode;
                name = name.toLowerCase();
                return `${name.charAt(0).toUpperCase()}${name.substring(1, name.length)}`;
            },
            onDetailBtn(row) {
                this.dataId = row.id;
                this.$toOtherRouter({
                    name: `detailProductionReport`,
                    query: {
                        id: row.id
                    }
                });
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                this.getStatisticPayload();
                return this.apiItem['page'](this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.getErrorInfoRequest({ state: 0 });
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                        this.$nextTick(() => {
                            this.$refs.jkTable.$refs.xTable.refreshColumn();
                        });
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            },
            /** 新增按钮操作 */
            onAddBtn() {
                this.$toOtherRouter({
                    name: `addProductionReport`,
                    query: {
                        workshopId: this.searchParams.workshopId,
                        processId: this.processList.find(x => x.code === this.searchParams.processCode) ? this.processList.find(x => x.code === this.searchParams.processCode).id : null
                    }
                });
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.dataId = row.id;
                this.$toOtherRouter({
                    name: `editProductionReport`,
                    query: {
                        id: row.id
                    }
                });
            },

            /** 删除按钮操作 */
            onDeleteBtn(row) {
                this.apiItem['delete']({ id: row.id }).then((res) => {
                    if (res.data.status === 200) {
                        this.getListRequest();
                        this.$tipsBar(this, 'delete');
                    }
                }).catch(() => {});
            },
            onWorkshopChange(val) {
                this.$set(this.searchParams, 'processCode', '');
                this.getProcessData(val);

                this.$set(this.searchParams, 'shiftId', null);
                this.shiftList = [];
                this.getShiftListByWorkshopRequest();
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = { ...this.searchParams };
                params.pageNo = null;
                params.pageSize = null;
                this.$confirm('是否确认导出所有数据项?', { type: 'warning' }).then(() => {
                    this.exportLoading = true;
                    return this.apiItem['exportExcel'](params);
                }).then(res => {
                    if (res.data.status === 200) {
                        this.$download.excel(res, `${this.$route.meta.name}.xls`);
                        this.exportLoading = false;
                    }
                }).catch(() => {});
            },
            getProcessData(val) {
                this.garbledProcess = [];
                this.processList.forEach(y => {
                    if (val === y.workshopId) {
                        this.garbledProcess.push(y);
                    }
                });
            },
            // 获取区域的班次
            getShiftListByWorkshopRequest() {
                this.shiftList = [];
                if (!this.searchParams.workshopId) return;
                return workforcemanagementShiftPage({
                    workshopId: this.searchParams.workshopId
                }).then(res => {
                    if (res.data.status === 200) {
                        this.shiftList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                await this.getShiftListByWorkshopRequest();
                await this.getMenuColumnListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            }
        },
        mounted() {
            this.processList = this.$store.state.user.userProcess.processList;
            this.workshopList = this.$store.state.user.userWorkshop.workshopList;
            // 默认值(页面缓存时，没有值的情况下再赋值)
            if (!this.searchParams.processCode) {
                this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode || '');
            }
            if (!this.searchParams.workshopId) {
                this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
            }
            this.getProcessData(this.$store.state.user.userWorkshop.defaultWorkshopId);
            this.getDependentData();
        }
    };
</script>
